package cc.mrbird.febs.system.service.impl;

import cc.mrbird.febs.common.authentication.JWTUtil;
import cc.mrbird.febs.common.domain.AreaManagerTree;
import cc.mrbird.febs.common.domain.FebsConstant;
import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.domain.Tree;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.utils.SortUtil;
import cc.mrbird.febs.common.utils.TreeUtil;
import cc.mrbird.febs.system.domain.*;
import cc.mrbird.febs.system.dao.TAreaManagerMapper;
import cc.mrbird.febs.system.service.AreaService;
import cc.mrbird.febs.system.service.ITAreaManagerService;
import cc.mrbird.febs.system.service.ITResidentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author dtwei
 */
@Service
public class TAreaManagerServiceImpl extends ServiceImpl<TAreaManagerMapper, TAreaManager> implements ITAreaManagerService {

    @Resource
    private AreaService areaService;

    @Resource
    private ITResidentService itResidentService;

    @Override
    public void createAreaManager(TAreaManager tAM) {
        tAM.setCreateTime(new Date());
        this.save(tAM);
    }

    @Override
    public void deleteByAreaId(List<String> ids) {
        if(!ids.isEmpty()) {
            LambdaQueryWrapper<TAreaManager> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(TAreaManager::getAreaId, ids);
            remove(queryWrapper);
        }
    }

    @Override
    public void updateAreaManager(TAreaManager tAM) throws Exception {
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        //获取当前用户
        String username = "";
        String userId = "";
        if (StringUtils.isNotBlank(token)) {
            username = JWTUtil.getUsername(token);
            userId = JWTUtil.getUserId(token);
        }

        Area tempArea = areaService.getById(tAM.getAreaId());
        if(tempArea == null) {
            String message = "更新失败：区域不存在";
            Exception e = new FebsException(message);
            log.error(message, e);
            throw e;
        }
        TResident tRs = itResidentService.getById(tAM.getRsId());
        if(tRs == null) {
            String message = "更新失败：居民不存在";
            Exception e = new FebsException(message);
            log.error(message, e);
            throw e;
        }
        UpdateWrapper<TAreaManager> upWrp = new UpdateWrapper<>();
        upWrp.set("AREA_ID", tAM.getAreaId());
        upWrp.set("RS_ID", tAM.getRsId());
        upWrp.set("MODIFY_TIME", new Date());
        upWrp.set("MODIFY_USERNAME", username);
        upWrp.set("MODIFY_USER_ID", userId);
        this.baseMapper.update(null, upWrp);
    }

    @Override
    public List<TAreaManager> findAreaManagerList(TAreaManager tAM) {
        LambdaQueryWrapper<TAreaManager> queryWrapper = new LambdaQueryWrapper<>();
        findAreaManagerCondition(queryWrapper, tAM);
        queryWrapper.orderByDesc(TAreaManager::getModifyTime);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public void updateAfterDelAreaManager(Long areaId, List<TResident> residents) {
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        //获取当前用户
        Map<String, String> creartInfo = new HashMap<>();
        if (StringUtils.isNotBlank(token)) {
            creartInfo.put("userName", JWTUtil.getUsername(token));
            creartInfo.put("userId", JWTUtil.getUserId(token));
        }
        //删除原有的区域管理员
        LambdaQueryWrapper<TAreaManager> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TAreaManager::getAreaId, areaId);
        this.baseMapper.delete(queryWrapper);
        //新增区域管理员
        List<TAreaManager> ars = new ArrayList<>();
        residents.forEach(rsi -> {
            TAreaManager taTmp = new TAreaManager();
            taTmp.setAreaId(areaId);
            taTmp.setRsId(rsi.getId());
            taTmp.setCreateTime(new Date());
            taTmp.setCreateUsername(creartInfo.get("userName"));
            taTmp.setCreateUserId(Long.valueOf(creartInfo.get("userId")));
            ars.add(taTmp);
        });
        this.baseMapper.insertList(ars);
    }

    private void findAreaManagerCondition(LambdaQueryWrapper<TAreaManager> queryWrapper, TAreaManager tAM) {
        if (tAM.getRsId() != null) {
            queryWrapper.eq(TAreaManager::getRsId, tAM.getRsId());
        }
        if (tAM.getAreaId() != null) {
            queryWrapper.eq(TAreaManager::getAreaId, tAM.getAreaId());
        }
    }

}
